package com.geezdata.cps.base.validator;

import java.lang.reflect.InvocationTargetException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.beanutils.BeanUtils;

import com.geezdata.cps.base.annotation.NotNullIfAnotherFieldIsNull;

/*
@NotNullIfAnotherFieldIsNull.List({
    @NotNullIfAnotherFieldIsNull(
        fieldName = "status",
        dependFieldName = "fieldOne"),
    @NotNullIfAnotherFieldIsNull(
        fieldName = "status",
        dependFieldName = "fieldTwo")
})
public class SampleBean {
    private String status;
    private String fieldOne;
    private String fieldTwo;

    // getters and setters omitted
}
*/
public class NotNullIfAnotherFieldIsNullValidator
	implements ConstraintValidator<NotNullIfAnotherFieldIsNull, Object> {

	private String fieldName;
	private String dependFieldName;
	
	@Override
	public void initialize(final NotNullIfAnotherFieldIsNull annotation) {
	    fieldName          = annotation.fieldName();
	    dependFieldName    = annotation.dependFieldName();
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext ctx) {
	
	    if (value == null) {
	        return true;
	    }
	
	    try {
	        String fieldValue       = BeanUtils.getProperty(value, fieldName);
	        String dependFieldValue = BeanUtils.getProperty(value, dependFieldName);
	
	        if (fieldValue == null && dependFieldValue == null) {
	            ctx.disableDefaultConstraintViolation();
	            ctx.buildConstraintViolationWithTemplate(ctx.getDefaultConstraintMessageTemplate())
	                .addPropertyNode(dependFieldName)
	                .addConstraintViolation();
	                return false;
	        }
	
	    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
	        throw new RuntimeException(ex);
	    }
	
	    return true;
	}

}